<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) 2016-2017 http://www.clcw.com.cn All rights reserved.    |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                           |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: Xmh <xiangminghu@clcw.com.cn>                                  |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\Other;

use AuctionCore\CarResource\CarModel as CarModel;
use AuctionCore\System\AuctionException;

/**
 * 第三方工具
 * @author  Xmh
 */
class Tools {

    private $MyCarModel;
    private $che300_token = '209e0bb5ef49fe9958fb4a429b99bd1c';
    private $baidu_appkey = 'ywUqWwMV6VG4dPP4OjhAh8TMhbnO2u1H';
    private $haoservice_weather_appkey = '3d368fd6e9b24c1eb10926a0edcbe9a7';
    private $haoservice_limit_line_appkey = 'c4257bdbde6149c6996d4e901e119a85';
    private $haoservice_oil_price_appkey = '890709fe08d24e1783781185b5f736a3';
    private $jisu_appkey = '5d0c7cbb089fd227';

    public function __construct() {
        $this->MyCarModel = M('mycar');
        $this->CarModel = new CarModel();
    }

    /**
     * 获取用户添加的爱车信息
     * @param type $uid
     * @return array
     */
    public function get_mycar($uid) {
        $condition['uid'] = $uid;
        $cols = 'mycar_id,city_code,plate_prefix,plate_suffix,engine_number,frame_number';
        return $this->MyCarModel->field($cols)->where($condition)->find();
    }

    /**
     * 用户添加爱车
     * @param type $data
     * @return int
     */
    public function add_mycar($data) {
        $where['plate_suffix'] = array('eq', $data['plate_suffix']);
        $where['engine_number'] = array('eq', $data['engine_number']);
        $where['frame_number'] = array('eq', $data['frame_number']);
        $where['_logic'] = 'or';
        $map['_complex'] = $where;
        $map['uid'] = array('eq', $data['uid']);
        $count = $this->MyCarModel->where($map)->count();
        if ($count >= 1) {
            AuctionException::make_throw('1200003');
        }
        return $this->MyCarModel->add($data);
    }

    public function edit_mycar($data) {
        return $this->MyCarModel->save($data);
    }

    public function del_mycar($mycar_id) {
        return $this->MyCarModel->delete($mycar_id);
    }

    /**
     * 根据经纬度获取城市信息(Baidu MAP API)
     * @param type $longitude 经度
     * @param type $latitude 纬度
     * @return type
     */
    public function get_location($longitude, $latitude) {
        $domain = 'http://api.map.baidu.com/';
        $service_name = 'geocoder';
        $version = 'v2';
        $post_url = $domain . $service_name . '/' . $version . '/?ak=' . $this->baidu_appkey . '&callback==showLocation&location=' . $latitude . ',' . $longitude . '&output=json';
        return curlPost($post_url, '');
    }

    /**
     * 根据定位返回的city_id得到与本库对应的城市city_code和city_name
     * @param int $baidu_city_code 城市编号
     * @return array
     */
    public function get_city_by_baidumap($baidu_city_code) {
        $condition['baidu_city_code'] = $baidu_city_code;
        $city = M("baidu_city")->field('city_code,city_name')->where($condition)->find();
        return $city;
    }

    /**
     * 保存百度cityCode与本库映射
     */
    public function save_baidumap_citycode() {
        $file_path = "/home/xiangminghu/job/php-prj/paimai/Public/SiteApi/BaiduMap/BaiduMap_cityCode_2.txt";
        $baidu_city_str = file_get_contents($file_path);
        $baidu_city_arr = explode(",", trim($baidu_city_str));
        foreach ($baidu_city_arr as $k => $c) {
            $city_name_arr[$k] = explode('-', trim($c));
        }
        $local_city = M('addr_area')->field('city_code,city_name,province')->where('level=1')->select();
        foreach ($local_city as $lcv) {
            foreach ($city_name_arr as $cnv) {
                if ($lcv[province] == $cnv[1]) {
                    $data['city_code'] = $lcv['city_code'];
                    $data['city_name'] = $lcv['city_name'];
                    $data['baidu_city_code'] = $cnv[0];
                    $condition['city_code'] = $lcv['city_code'];
                    $total = M('baidu_city')->where($condition)->count();
                    if ($total < 1) {
                        $res = M('baidu_city')->add($data);
                        if ($res) {
                            echo date("Y-m-d H:i:s") . "数据插入成功<br/>";
                        } else {
                            echo date("Y-m-d H:i:s") . "数据插入失败<br/>";
                        }
                    } else {
                        echo date("Y-m-d H:i:s") . "数据已存在<br/>";
                    }
                }
            }
        }
    }

    /**
     * 违章 -- 极速数据
     */
    public function get_weizhang_byjisu($post_info) {
        $jisu_url = 'http://api.jisuapi.com/illegal/query?appkey=' . $this->jisu_appkey;
        return curlPost($jisu_url, $post_info);
    }

    /**
     * 违章  -- 获取城市交管局
     */
    public function get_city_carorg_byjisu() {
        $jisu_url = 'http://api.jisuapi.com/illegal/carorg?appkey=' . $this->jisu_appkey . '&onlysupport=1';
        return curlGet($jisu_url);
    }

    /**
     * 车首页 -- 查违章
     * @param type $car_info
     */
    public static function get_weizhang($car_info) {
        $app_id = '1516';
        $app_key = 'd0d1aeaaca37eb1ea6f8e1065f6565e1';
        $post_url = "http://www.cheshouye.com/api/weizhang/query_task";
        list($sec, $micro) = explode(" ", microtime());
        $timestamp = ceil(((float) $sec + (float) $micro) * 1000);
        $sign_str = $app_id . $car_info . $timestamp . $app_key;
        $sign = md5($sign_str);
        try {
            $data['car_info'] = urlencode($car_info);
            $data['sign'] = $sign;
            $data['timestamp'] = $timestamp;
            $data['app_id'] = $app_id;
            $res = curlPost($post_url, $data);
            return $res;
        } catch (Exception $e) {
            echo $e->getMessage();
        }
    }

    /**
     * 获取支持违章城市列表
     * @return array()
     */
    public function get_weizhang_city_byHaoService() {
        $app_key = "785b138a6eed47cfacac95adfe7ef226";
        $api_url = "http://apis.haoservice.com/weizhang/citys?key=" . $app_key;
        return curlGet($api_url);
    }

    /**
     * 获取违章
     * @param type $city
     * @param type $plate_number
     * @param type $engine_number
     */
    public function get_weizhang_byHaoService($city, $plate_number, $engine_number, $frame_number) {
        $app_key = "785b138a6eed47cfacac95adfe7ef226";
        $api_url = "http://apis.haoservice.com/weizhang/query?city=" . $city
                . "&hphm=" . $plate_number . "&hpzl=02&engineno=" . $engine_number . "&classno=" . $frame_number . "&registno=&key=" . $app_key;
        return curlGet($api_url);
    }

    /**
     * 获取支持天气的城市
     */
    public function get_weather_city_byHaoService() {
        $api_url = "http://apis.haoservice.com/weather/city?key=" . $this->haoservice_weather_appkey;
        return curlGet($api_url);
    }

    /**
     * 获取天气标识
     * @return array
     */
    public function get_weather_sign_byHaoService() {
        $api_url = "http://apis.haoservice.com/weather/uni?key=" . $this->haoservice_weather_appkey;
        return curlGet($api_url);
    }

    /**
     * 根据城市获取一周天气
     * @param string $cityname 城市名称
     * @return Array
     */
    public function get_weather_byHaoService($cityname) {
        $api_url = "http://apis.haoservice.com/weather?key=" . $this->haoservice_weather_appkey . "&cityname=" . $cityname;
        return curlGet($api_url);
    }

    /**
     * 获取尾号限行城市列表
     * @return array
     */
    public function get_limit_city_byHaoService() {
        $api_url = "http://apis.haoservice.com/carservice/xianxing?key=" . $this->haoservice_limit_line_appkey;
        return curlGet($api_url);
    }

    /**
     * 根据城市id获取限行
     * @param int $city_code 城市代码
     * @return array
     */
    public function get_limit_line_byHaoService($city_code) {
        $api_url = "http://apis.haoservice.com/carservice/xianxing/query?key=" . $this->haoservice_limit_line_appkey . "&cityId=" . $city_code;
        return curlGet($api_url);
    }

    /**
     * 根据经纬度查周边油价格
     * @param float $longitude 经度
     * @param float $latitude  纬度
     * return array
     */
    public function get_local_oil_byHaoService($longitude, $latitude) {
        $api_url = "http://apis.haoservice.com/oil/local?lon=" . $longitude . "&lat=" . $latitude . "&r=3000&page=1&key=" . $this->haoservice_oil_price_appkey;
        return curlGet($api_url);
    }


    /**
     * 从车300获取车品牌列表
     */
    public function get_brand_list_byChe300() {
        $che300_post_url = 'http://api.che300.com/service/getCarBrandList?token=' . $this->che300_token;
        $brand_list = curlGet($che300_post_url);
        return $brand_list;
    }

    /**
     * 从车300获取车系列表
     */
    public function get_series_list_byChe300($brand_id) {
        $che300_post_url = 'http://api.che300.com/service/getCarSeriesList?token=' . $this->che300_token . "&brandId=" . $brand_id;
        $series_list = curlGet($che300_post_url);
        return $series_list;
    }

    /**
     * 从车300获取车车型列表
     */
    public function get_model_list_byChe300($series_id) {
        $che300_post_url = 'http://api.che300.com/service/getCarModelList?token=' . $this->che300_token . "&seriesId=" . $series_id;
        $model_list = curlGet($che300_post_url);
        return $model_list;
    }

    /**
     * 从车300获取城市列表
     */
    public function get_city_list_byChe300() {
        $che300_post_url = 'http://api.che300.com/service/getAllCity?token=' . $this->che300_token;
        $city_list = curlGet($che300_post_url);
        return $city_list;
    }

    /**
     * 根据选择的城市ID获取车300的地区ID
     * @param type $address
     */
    public static function get_che300_city_zone($address) {
        if (!is_numeric($address)) {
            AuctionException::make_throw('1200002');
        }
        $condition['city_code'] = $address;
        $zone = M('che300_city')->field('che300_city_code')->where($condition)->find();
        return $zone['che300_city_code'];
    }

    /**
     * 车300地区与本库映射关系存到che300_city库
     */
    public function get_che300_city() {
        $addr_level_0 = M('addr_area')->field('city_code,city_name')->where('level=0')->select();
        $addr = M('addr_area')->field('city_code,city_name')->where('level=1')->select();
        $che300_city = curlGet("http://api.che300.com/service/getAllCity?token=" . $this->token, true);
        $province = array();
        foreach ($addr as $a) {
            foreach ($che300_city['city_list'] as $k => $c) {
                $province[$k]['prov_id'] = $c['prov_id'];
                $province[$k]['prov_name'] = $c['prov_name'];
                if ($a['city_name'] == $c['city_name']) {
//                    echo $a['city_code'].$a['city_name'] .'=='. $c['city_id'].$c['city_name']."<br>";
                    $data['city_name'] = $a['city_name'];
                    $data['city_code'] = $a['city_code'];
                    $data['che300_city_code'] = $c['city_id'];
                    $total = M('che300_city')->where('city_code=' . $data['city_code'])->count();
                    if ($total <= 0) {
                        $rel_id = M('che300_city')->add($data);
                        echo "插入数据成功" . $rel_id . "<br/>";
                    } else {
                        echo "数据已经存在<br>";
                    }
                }
            }
        }
        $province_arr = $this->array_unique_2d($province);
        foreach ($addr_level_0 as $a) {
            foreach ($province_arr as $p) {
                if ($a['city_name'] == $p['prov_name']) {
                    echo $a['city_code'] . $a['city_name'] . '==' . $p['prov_id'] . $p['prov_name'] . "<br>";
                    $data['city_name'] = $a['city_name'];
                    $data['city_code'] = $a['city_code'];
                    $data['che300_city_code'] = $p['prov_id'];
                    $total = M('che300_city')->where('city_code=' . $data['city_code'])->count();
                    if ($total <= 0) {
                        $rel_id = M('che300_city')->add($data);
                        echo "插入数据成功" . $rel_id . "<br/>";
                    } else {
                        echo "数据已经存在<br>";
                    }
                }
            }
        }
    }

    /**
     * 二维数组去重复
     * @param type $array
     * @return type
     */
    public function array_unique_2d($array) {
        foreach ($array as $key => $val) {
            $i = 0;
            foreach ($array as $k => $v) {
                $diff = json_encode($val) == json_encode($v);
                if ($diff && $i == 0) {
                    $i++;
                    continue;
                } else if ($diff) {
                    unset($array[$k]);
                }
            }
        }
        return $array;
    }

    /**
     * 根据本库的model_id获取che300的model_id
     * @param type $model_id
     */
    public static function get_model_to_che300model($model_id) {
        $condition['model_id'] = $model_id;
        $che300model_id = M("che300_model")->where($condition)->getField('che300_model_id');
        return $che300model_id;
    }

    /**
     * che300 API获取model
     * 根据车品牌、车系、车型信息获得车300对应的车型model_id
     */
    public function get_model_id_byche300() {
        $model_id = '1'; //I('post.model_id');
        $model = $this->CarModel->get_parent_brand_info($model_id);
        $brand = trim($model['brand']['name']);
        $series = trim($model['series']['name']);
        $model_name = trim(str_replace(' ', '', $model['model']['name']));
        $year = intval(trim($model['model']['year']));
        $post_url = "http://api.che300.com/service/identifyModel?token=209e0bb5ef49fe9958fb4a429b99bd1c&brand="
                . $brand . "&series=" . $series . "&model=" . $model_name . "&modelYear=" . $year;
        $res = curlGet($post_url);
        if ($res['status'] === '1') {
            return $res['modelInfo']['model_id'];
        } else {
            AuctionException::make_throw('请求数据失败,请稍后再试');
        }
    }
}
